package com.centaline.androidsalesblog.activities.mine;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatTextView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.adapter.TabFragmentAdapter;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.fragments.calculate.LoanBusinessFragment;
import com.centaline.androidsalesblog.fragments.calculate.LoanCombFragment;
import com.centaline.androidsalesblog.fragments.calculate.LoanFundFragment;
import com.centaline.androidsalesblog.iml.LoanCalculateCallback;
import com.centaline.androidsalesblog.model.businissobject.LoanCalculateBo;
import com.centaline.androidsalesblog.utils.CalculateUtil;
import com.centaline.androidsalesblog.widgets.chart.LoanPieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;

import java.util.ArrayList;
import java.util.Locale;

/**
 * 房贷计算器
 * Created by Ruan on 2016/2/23.
 */
public class LoanCalcActivity extends BaseActivity implements View.OnClickListener {

    private final int Color1 = Color.rgb(255, 225, 85);
    private final int Color2 = Color.rgb(255, 54, 21);
    private final int Color3 = Color.rgb(69, 176, 237);

    private TabLayout tl_calc;
    private ViewPager vp_loan_calc;
    private View overView;
    private BottomSheetBehavior bottomSheetBehavior;
    private LinearLayout ll_result;
    private LoanPieChart loanPieChart;
    private AppCompatTextView atv_title1, atv_des1, atv_title2, atv_des2, atv_title3, atv_des3,
            atv_title4, atv_des4, atv_title5, atv_des5;

    private LoanCalculateCallback loanCalculateCallback = new LoanCalculateCallback() {
        @Override
        public void callBack(LoanCalculateBo loanCalculateBo) {
            calculateResult(loanCalculateBo);
        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.activity_loan_calc;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        tl_calc = (TabLayout) findViewById(R.id.tl_calc);
        vp_loan_calc = (ViewPager) findViewById(R.id.vp_loan_calc);
        overView = findViewById(R.id.overView);
        ll_result = (LinearLayout) findViewById(R.id.ll_result);
        loanPieChart = (LoanPieChart) findViewById(R.id.loanPieChart);
        atv_title1 = (AppCompatTextView) findViewById(R.id.atv_title1);
        atv_des1 = (AppCompatTextView) findViewById(R.id.atv_des1);
        atv_title2 = (AppCompatTextView) findViewById(R.id.atv_title2);
        atv_des2 = (AppCompatTextView) findViewById(R.id.atv_des2);
        atv_title3 = (AppCompatTextView) findViewById(R.id.atv_title3);
        atv_des3 = (AppCompatTextView) findViewById(R.id.atv_des3);
        atv_title4 = (AppCompatTextView) findViewById(R.id.atv_title4);
        atv_des4 = (AppCompatTextView) findViewById(R.id.atv_des4);
        atv_title5 = (AppCompatTextView) findViewById(R.id.atv_title5);
        atv_des5 = (AppCompatTextView) findViewById(R.id.atv_des5);
    }

    @Override
    protected void initViews() {
        bottomSheetBehavior = BottomSheetBehavior.from(ll_result);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                overView.setAlpha(slideOffset);
                overView.setVisibility(slideOffset > 0 ? View.VISIBLE : View.GONE);
            }
        });

        ArrayList<String> mTitleList = new ArrayList<>();
        mTitleList.add("商业贷款");
        mTitleList.add("公积金贷款");
        mTitleList.add("组合贷款");

        ArrayList<Fragment> fragmentList = new ArrayList<>();
        LoanBusinessFragment loanBusinessFragment = new LoanBusinessFragment();
        loanBusinessFragment.setLoanCalculateCallback(loanCalculateCallback);
        LoanFundFragment loanFundFragment = new LoanFundFragment();
        loanFundFragment.setLoanCalculateCallback(loanCalculateCallback);
        LoanCombFragment loanCombFragment = new LoanCombFragment();
        loanCombFragment.setLoanCalculateCallback(loanCalculateCallback);
        fragmentList.add(loanBusinessFragment);
        fragmentList.add(loanFundFragment);
        fragmentList.add(loanCombFragment);

        Bundle bundle = getIntent().getBundleExtra(ExtraConstant.LOAN_BUNDLE);
        if (bundle != null) {
            loanBusinessFragment.setArguments(bundle);
            loanFundFragment.setArguments(bundle);
        }

        vp_loan_calc.setAdapter(new TabFragmentAdapter(getSupportFragmentManager(),
                fragmentList, mTitleList));
        tl_calc.setupWithViewPager(vp_loan_calc);
    }

    /**
     * 计算结果
     */
    private void calculateResult(LoanCalculateBo loanCalculateBo) {
        ArrayList<String> xValues = new ArrayList<>();  //xValues用来表示每个饼块上的内容
        ArrayList<Entry> yValues = new ArrayList<>();  //yValues用来表示封装每个饼块的实际数据
        ArrayList<Integer> colors = new ArrayList<>();//饼图颜色

        int modeType = loanCalculateBo.getModeType();
        int loanType = loanCalculateBo.getLoanType();
        int month = loanCalculateBo.getMonth();
        boolean businessRateEnable = loanCalculateBo.getBusinessRate() != 0;
        double rate = businessRateEnable ?
                loanCalculateBo.getBusinessRate() : loanCalculateBo.getFundRate();
        switch (modeType) {
            case 0://贷款总额
                if (loanType == 0) {//等额本息
                    double per = CalculateUtil.countBenXi(
                            loanCalculateBo.getBusinessPrice() * 10000,
                            rate / 100,
                            month);
                    double daikuan = loanCalculateBo.getBusinessPrice();
                    double totalLixi = per * month - daikuan * 10000;
                    double total = totalLixi + daikuan * 10000;
                    xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "贷款总额", daikuan));
                    if (totalLixi > 10000) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "利息总额", totalLixi / 10000));
                    } else {
                        xValues.add(String.format(Locale.CHINA, "%s : %.0f元", "利息总额", totalLixi));
                    }
                    yValues.add(new Entry((float) (daikuan * 10000 / total), 0));
                    yValues.add(new Entry(totalLixi / total < 0.01 ? 0.01f : (float) (totalLixi / total), 1));
                    colors.add(Color1);
                    colors.add(Color2);

                    setPieChartDefault(xValues, yValues, colors, per, "参考月供");

                    atv_title1.setText("贷款年数");
                    atv_des1.setText(String.format(Locale.CHINA, "%d年(%d期)", month / 12, month));
                    atv_title2.setText(businessRateEnable ? "商贷利率" : "公积金利率");
                    atv_des2.setText(String.format(Locale.CHINA, "%.2f%%", rate));
                    atv_title3.setText("");
                    atv_des3.setText("");
                    atv_title4.setText("");
                    atv_des4.setText("");
                    atv_title5.setText("");
                    atv_des5.setText("");
                } else {//等额本金
                    double daikuan = loanCalculateBo.getBusinessPrice();
                    double benjin = CalculateUtil.countBenJin(
                            daikuan * 10000,
                            rate / 100,
                            month);
                    double start = CalculateUtil.countBenJin4Month(
                            daikuan * 10000,
                            rate / 100,
                            month,
                            1);
                    double end = CalculateUtil.countBenJin4Month(
                            daikuan * 10000,
                            rate / 100,
                            month,
                            month);
                    double perBenjin = benjin / month;
                    double totalLixi = benjin - daikuan * 10000;
                    double total = totalLixi + daikuan * 10000;
                    xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "贷款总额", daikuan));
                    if (totalLixi > 10000) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "利息总额", totalLixi / 10000));
                    } else {
                        xValues.add(String.format(Locale.CHINA, "%s : %.0f元", "利息总额", totalLixi));
                    }
                    yValues.add(new Entry((float) (daikuan * 10000 / total), 0));
                    yValues.add(new Entry(totalLixi / total < 0.01 ? 0.01f : (float) (totalLixi / total), 1));
                    colors.add(Color1);
                    colors.add(Color2);

                    setPieChartDefault(xValues, yValues, colors, perBenjin, "平均月供");

                    atv_title1.setText("贷款年数");
                    atv_des1.setText(String.format(Locale.CHINA, "%d年(%d期)", month / 12, month));
                    atv_title2.setText(businessRateEnable ? "商贷利率" : "公积金利率");
                    atv_des2.setText(String.format(Locale.CHINA, "%.2f%%", rate));
                    atv_title3.setText("首月还贷");
                    atv_des3.setText(String.format(Locale.CHINA, "%.2f元", start));
                    atv_title4.setText("末月还贷");
                    atv_des4.setText(String.format(Locale.CHINA, "%.2f元", end));
                    atv_title5.setText("");
                    atv_des5.setText("");
                }
                break;
            case 1://按揭
                if (loanType == 0) {//等额本息
                    double per = CalculateUtil.countBenXi(
                            loanCalculateBo.getTotalPrice() * (10 - loanCalculateBo.getRatio()) * 1000,
                            rate / 100,
                            month);
                    double shoufu = loanCalculateBo.getTotalPrice() * loanCalculateBo.getRatio() / 10;
                    double daikuan = loanCalculateBo.getTotalPrice() * (10 - loanCalculateBo.getRatio()) / 10;
                    double totalLixi = per * month - daikuan * 10000;
                    double total = totalLixi + shoufu * 10000 + daikuan * 10000;
                    xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "首付", shoufu));
                    xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "贷款总额", daikuan));
                    if (totalLixi > 10000) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "利息总额", totalLixi / 10000));
                    } else {
                        xValues.add(String.format(Locale.CHINA, "%s : %.0f元", "利息总额", totalLixi));
                    }
                    yValues.add(new Entry((float) (shoufu * 10000 / total), 0));
                    yValues.add(new Entry((float) (daikuan * 10000 / total), 1));
                    yValues.add(new Entry(totalLixi / total < 0.01 ? 0.01f : (float) (totalLixi / total), 2));
                    colors.add(Color1);
                    colors.add(Color2);
                    colors.add(Color3);

                    setPieChartDefault(xValues, yValues, colors, per, "参考月供");

                    atv_title1.setText("房屋总价");
                    atv_des1.setText(String.format(Locale.CHINA, "%.0f万", loanCalculateBo.getTotalPrice()));
                    atv_title2.setText("贷款年数");
                    atv_des2.setText(String.format(Locale.CHINA, "%d年(%d期)", month / 12, month));
                    atv_title3.setText(businessRateEnable ? "商贷利率" : "公积金利率");
                    atv_des3.setText(String.format(Locale.CHINA, "%.2f%%", rate));
                    atv_title4.setText("");
                    atv_des4.setText("");
                    atv_title5.setText("");
                    atv_des5.setText("");
                } else {//等额本金
                    double benjin = CalculateUtil.countBenJin(
                            loanCalculateBo.getTotalPrice() * (10 - loanCalculateBo.getRatio()) * 1000,
                            rate / 100,
                            month);
                    double start = CalculateUtil.countBenJin4Month(
                            loanCalculateBo.getTotalPrice() * (10 - loanCalculateBo.getRatio()) * 1000,
                            rate / 100,
                            month,
                            1);
                    double end = CalculateUtil.countBenJin4Month(
                            loanCalculateBo.getTotalPrice() * (10 - loanCalculateBo.getRatio()) * 1000,
                            rate / 100,
                            month,
                            month);
                    double perBenjin = benjin / month;
                    double shoufu = loanCalculateBo.getTotalPrice() * loanCalculateBo.getRatio() / 10;
                    double daikuan = loanCalculateBo.getTotalPrice() * (10 - loanCalculateBo.getRatio()) / 10;
                    double totalLixi = benjin - daikuan * 10000;
                    double total = totalLixi + shoufu * 10000 + daikuan * 10000;
                    xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "首付", shoufu));
                    xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "贷款总额", daikuan));
                    if (totalLixi > 10000) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "利息总额", totalLixi / 10000));
                    } else {
                        xValues.add(String.format(Locale.CHINA, "%s : %.0f元", "利息总额", totalLixi));
                    }
                    yValues.add(new Entry((float) (shoufu * 10000 / total), 0));
                    yValues.add(new Entry((float) (daikuan * 10000 / total), 1));
                    yValues.add(new Entry((float) totalLixi / total < 0.01 ? 0.01f : (float) (totalLixi / total), 2));
                    colors.add(Color1);
                    colors.add(Color2);
                    colors.add(Color3);

                    setPieChartDefault(xValues, yValues, colors, perBenjin, "平均月供");

                    atv_title1.setText("房屋总价");
                    atv_des1.setText(String.format(Locale.CHINA, "%.0f万", loanCalculateBo.getTotalPrice()));
                    atv_title2.setText("贷款年数");
                    atv_des2.setText(String.format(Locale.CHINA, "%d年(%d期)", month / 12, month));
                    atv_title3.setText(businessRateEnable ? "商贷利率" : "公积金利率");
                    atv_des3.setText(String.format(Locale.CHINA, "%.2f%%", rate));
                    atv_title4.setText("首月还贷");
                    atv_des4.setText(String.format(Locale.CHINA, "%.2f元", start));
                    atv_title5.setText("末月还贷");
                    atv_des5.setText(String.format(Locale.CHINA, "%.2f元", end));
                }
                break;
            case 2:
                double bPrice = loanCalculateBo.getBusinessPrice();
                double bRate = loanCalculateBo.getBusinessRate() / 100;
                double fPrice = loanCalculateBo.getFundPrice();
                double fRate = loanCalculateBo.getFundRate() / 100;
                if (loanType == 0) {//等额本息
                    double per = CalculateUtil.countBenXi(bPrice * 10000,
                            bRate, month) +
                            CalculateUtil.countBenXi(fPrice * 10000,
                                    fRate, month);
                    double lixi = per * month - bPrice * 10000 - fPrice * 10000;
                    double total = lixi + bPrice * 10000 + fPrice * 10000;
                    if (fPrice > 0) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "公积金贷款", fPrice));
                    }
                    if (bPrice > 0) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "商业贷款", bPrice));
                    }
                    if (lixi > 10000) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "利息总额", lixi / 10000));
                    } else {
                        xValues.add(String.format(Locale.CHINA, "%s : %.0f元", "利息总额", lixi));
                    }
                    if (fPrice > 0) {
                        yValues.add(new Entry((float) (fPrice * 10000 / total), 0));
                        if (bPrice > 0) {
                            yValues.add(new Entry((float) (bPrice * 10000 / total), 1));
                            yValues.add(new Entry((float) (lixi / total), 2));
                        } else {
                            yValues.add(new Entry((float) (lixi / total), 1));
                        }
                    } else {
                        yValues.add(new Entry((float) (bPrice * 10000 / total), 0));
                        yValues.add(new Entry((float) (lixi / total), 1));
                    }

                    colors.add(Color1);
                    colors.add(Color2);
                    if (yValues.size() > 2) {
                        colors.add(Color3);
                    }

                    setPieChartDefault(xValues, yValues, colors, per, "参考月供");

                    atv_title1.setText("贷款年数");
                    atv_des1.setText(String.format(Locale.CHINA, "%d年(%d期)", month / 12, month));
                    if (bPrice > 0) {
                        atv_title2.setText("商贷利率");
                        atv_des2.setText(String.format(Locale.CHINA, "%.2f%%", bRate * 100));
                        if (fPrice > 0) {
                            atv_title3.setText("公积金利率");
                            atv_des3.setText(String.format(Locale.CHINA, "%.2f%%", fRate * 100));
                        } else {
                            atv_title3.setText("");
                            atv_des3.setText("");
                        }
                    } else {
                        atv_title2.setText("公积金利率");
                        atv_des2.setText(String.format(Locale.CHINA, "%.2f%%", fRate * 100));
                        atv_title3.setText("");
                        atv_des3.setText("");
                    }
                    atv_title4.setText("");
                    atv_des4.setText("");
                    atv_title5.setText("");
                    atv_des5.setText("");
                } else {//等额本金
                    double benjin = CalculateUtil.countBenJin(bPrice * 10000, bRate, month) +
                            CalculateUtil.countBenJin(fPrice * 10000, fRate, month);
                    double start = CalculateUtil.countBenJin4Month(bPrice * 10000, bRate, month, 1) +
                            CalculateUtil.countBenJin4Month(fPrice * 10000, fRate, month, 1);
                    double end = CalculateUtil.countBenJin4Month(bPrice * 10000, bRate, month, month) +
                            CalculateUtil.countBenJin4Month(fPrice * 10000, fRate, month, month);
                    double per = benjin / month;
                    double lixi = benjin - bPrice * 10000 - fPrice * 10000;
                    double total = lixi + bPrice * 10000 + fPrice * 10000;
                    if (fPrice > 0) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "公积金贷款", fPrice));
                    }
                    if (bPrice > 0) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "商业贷款", bPrice));
                    }
                    if (lixi > 10000) {
                        xValues.add(String.format(Locale.CHINA, "%s : %.2f万", "利息总额", lixi / 10000));
                    } else {
                        xValues.add(String.format(Locale.CHINA, "%s : %.0f元", "利息总额", lixi));
                    }
                    if (fPrice > 0) {
                        yValues.add(new Entry((float) (fPrice * 10000 / total), 0));
                        if (bPrice > 0) {
                            yValues.add(new Entry((float) (bPrice * 10000 / total), 1));
                            yValues.add(new Entry((float) (lixi / total), 2));
                        } else {
                            yValues.add(new Entry((float) (lixi / total), 1));
                        }
                    } else {
                        yValues.add(new Entry((float) (bPrice * 10000 / total), 0));
                        yValues.add(new Entry((float) (lixi / total), 1));
                    }
                    colors.add(Color1);
                    colors.add(Color2);
                    if (yValues.size() > 2) {
                        colors.add(Color3);
                    }

                    setPieChartDefault(xValues, yValues, colors, per, "平均月供");

                    atv_title1.setText("贷款年数");
                    atv_des1.setText(String.format(Locale.CHINA, "%d年(%d期)", month / 12, month));
                    if (bPrice > 0) {
                        atv_title2.setText("商贷利率");
                        atv_des2.setText(String.format(Locale.CHINA, "%.2f%%", bRate * 100));
                        if (fPrice > 0) {
                            atv_title3.setText("公积金利率");
                            atv_des3.setText(String.format(Locale.CHINA, "%.2f%%", fRate * 100));
                            atv_title4.setText("首月还贷");
                            atv_des4.setText(String.format(Locale.CHINA, "%.2f元", start));
                            atv_title5.setText("末月还贷");
                            atv_des5.setText(String.format(Locale.CHINA, "%.2f元", end));
                        } else {
                            atv_title3.setText("首月还贷");
                            atv_des3.setText(String.format(Locale.CHINA, "%.2f元", start));
                            atv_title4.setText("末月还贷");
                            atv_des4.setText(String.format(Locale.CHINA, "%.2f元", end));
                            atv_title5.setText("");
                            atv_des5.setText("");
                        }
                    } else {
                        atv_title2.setText("公积金利率");
                        atv_des2.setText(String.format(Locale.CHINA, "%.2f%%", fRate * 100));
                        atv_title3.setText("首月还贷");
                        atv_des3.setText(String.format(Locale.CHINA, "%.2f元", start));
                        atv_title4.setText("末月还贷");
                        atv_des4.setText(String.format(Locale.CHINA, "%.2f元", end));
                        atv_title5.setText("");
                        atv_des5.setText("");
                    }

                }
                break;
            default:
                break;
        }
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }

    /**
     * 设置饼图默认值
     */
    private void setPieChartDefault(ArrayList<String> xValues, ArrayList<Entry> yValues,
                                    ArrayList<Integer> colors, double perMonth, String centerText) {
        PieDataSet pieDataSet = new PieDataSet(yValues, "");
        pieDataSet.setSliceSpace(2f); //设置个饼状图之间的距离
        pieDataSet.setDrawValues(false);//不显示值
        pieDataSet.setColors(colors);
        pieDataSet.setSelectionShift(5f); // 选中时态溢出的长度

        loanPieChart.setData(new PieData(xValues, pieDataSet));
        loanPieChart.setCenterTextSize(12);
        loanPieChart.setCenterTextColor(Color.rgb(102, 102, 102));
        loanPieChart.setCenterText(String.format(Locale.CHINA, "%s\n%.2f元/月", centerText, perMonth));
        loanPieChart.invalidate();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.overView:
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
